package cn.com.miao.lynx.common.data.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.data.domain.AuditorAware;
import org.springframework.util.Assert;

import java.time.LocalDateTime;

import static cn.com.miao.lynx.common.core.constant.CommonConstant.MetaField.*;
import static cn.com.miao.lynx.common.core.constant.CommonConstant.System.*;

/**
 * EntityMetaObjectHandler
 * 元数据填充handler
 * @title: EntityMetaObjectHandler
 * @description:
 * @author: dengmiao
 * @create: 2019-12-26 15:38
 **/
public class EntityMetaObjectHandler implements MetaObjectHandler {

    private final AuditorAware auditorAware;

    public EntityMetaObjectHandler(AuditorAware auditorAware) {
        Assert.isTrue(auditorAware != null, "auditorAware is not defined");
        this.auditorAware = auditorAware;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName(FIELD_CREATE_BY, auditorAware.getCurrentAuditor().get(), metaObject);
        LocalDateTime date = LocalDateTime.now();
        setFieldValByName(FIELD_CREATE_TIME, date, metaObject);
        setFieldValByName(FIELD_UPDATE_BY, auditorAware.getCurrentAuditor().get(), metaObject);
        setFieldValByName(FIELD_UPDATE_TIME, date, metaObject);
        setFieldValByName(FIELD_DEL_STATUS, DELETE_FLAG_NORMAL, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime date = LocalDateTime.now();
        setFieldValByName(FIELD_UPDATE_BY, auditorAware.getCurrentAuditor().get(), metaObject);
        setFieldValByName(FIELD_UPDATE_TIME, date, metaObject);
    }
}
